package com.hjc.filter;

import com.alibaba.fastjson.JSON;
import com.hjc.entity.Result;
import com.hjc.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class LoginCheckFilter implements Filter {

    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

    //    1.白名单路径直接放行
    //    1.1创建白名单urlList
        List<String> urlList = new ArrayList();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/product/img-upload");

        String url = request.getServletPath();
        if (urlList.contains(url) || url.contains("/img/upload")) {
            filterChain.doFilter(request,response);
            return;
        }
        //    2.其他路径验证token是否存在
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //    2.1请求头中token存在并且未过期则放行
        if(StringUtils.hasText(token) && redisTemplate.hasKey(token)) {
            filterChain.doFilter(request,response);
            return;
        }else {
        //    2.2否则代表未登录或登录已过期,响应给前端
            Result result = Result.err(Result.CODE_ERR_UNLOGINED,"您还没有登录！");
            String jsonStr = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(jsonStr);
            out.flush();
            out.close();

        }
    }
}
